#!/usr/bin/env python
#-*- coding:utf-8 -*-

from flask import current_app
from flask import jsonify
from flask import request
import traceback
from . import stat_api as app


@app.route('/all_topic', methods=['GET'])
def all_topic():
    logger = current_app.config['logger'];
    statistics = current_app.config['statistics']
    try:
        data = statistics.all_topic();
        return jsonify({'status':True, 'data':data})
    except:
        current_app.config['logger'].error(traceback.format_exc())
        return jsonify({'status':False, 'data':{'error_info':traceback.format_exc()}})


@app.route('/topic', methods=['GET'])
def topic():
    logger = current_app.config['logger'];
    args = request.args
    statistics = current_app.config['statistics']
    try:
        start_time = args.get('start_time', None);
        end_time = args.get('end_time', None);
        topic_id = args.get('topic_id', 0);
        stat_type = args.get('type', 'daily');
        data = statistics.topic(topic_id, stat_type,start_time, end_time);
        return jsonify({'status':True, 'data': data})
    except Exception,e:
        logger.error(e.message)
        return jsonify({'status':False, 'data':{'error_info':e.message}})

@app.route('/server', methods=['GET'])
def server():
    args = request.args
    server_name = args.get('name', None)
    logger = current_app.config['logger']
    try:
        return jsonify({
            'status':True,
            'data':{
                'last_check_time':current_app.config['server_manager'].last_check_time,
                'servers':current_app.config['server_manager'].get_server_info(server_name)
            }
        })
    except Exception as e:
        logger.error(e.message)
        return jsonify({
            'status':False,
            'data': {'error_info':e.message}
        })
